#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/un.h>
#include <string.h>

int my_recv(int sockfd,char* buf,int length){

    int temp=0;
    int ftemp=0;

    while(1){
        
        ftemp=recv(sockfd,buf+temp,length - temp,0);//0 阻塞(发送的缓冲区满/网络阻塞);
        if(ftemp == -1){
            perror("my_send err");
            return -1;
        }if(ftemp == 0){
            return 0;
        }
        temp+=ftemp;
        if(temp >= length){
            break;
        }
        
    }
    return temp;
}


int main(void){
    int sockfd = socket(AF_UNIX,SOCK_STREAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    int on=1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &on, sizeof(on))) {
        perror("setsockopt");
        close(sockfd);
        return -1;
    }
   
    struct sockaddr_un addr;
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path,"mysocket");

    socklen_t addrlen= sizeof(addr);
    //绑定
    if(bind(sockfd,(struct sockaddr*)&addr,addrlen) == -1){
        perror("bind err");
        close(sockfd);
        return -1;
    }

    //监听
    if(listen(sockfd,5) == -1){
        perror("listen err");
        close(sockfd);
        unlink("mysocket");
        return -1;
    }
    printf("waiting client connect!\n");

    //响应连接
    struct sockaddr_in client_addr;
    socklen_t clientlen;
    int clientfd=accept(sockfd,(struct sockaddr*)&client_addr,&clientlen);
    if(clientfd < 0){
        perror("accept err");
        close(sockfd);
        unlink("mysocket");
        return -1;
    }
    printf("new connect comming\n");

    //收发数据
    char buf[64]={0};
    int ret=0;
    while(1){
        ret =my_recv(clientfd,buf,sizeof(buf));
        if(ret < 0){
            perror("recv err");
            
            continue;
        }else if(ret > 0){
            printf("recv data:%s\n",buf);
        }else{
            printf("perr quit\n");
            break;
        }
    }


    //关闭
    close(clientfd);
    close(sockfd);
    unlink("mysocket");


    return 0;
}
